

import React, { useState, useEffect } from 'react'
import { Form, Input, Row, Col, Button } from 'antd';
import { LockOutlined, PhoneOutlined } from '@ant-design/icons';
import { reg } from '../../utils/validate';
import { Link } from 'react-router-dom';
import { ajax } from '../../api';
import { toast } from '../../utils/common';
import { withRouter } from 'react-router-dom';
import { observer, inject } from 'mobx-react';

let timer: any = null

function LoginPhone({ history, user, location }: any) {
    const { userInfo, changeUserInfo } = user
    const [form] = Form.useForm()
    const [disabled, setDisabled] = useState<boolean>(true)
    let [count, setCount] = useState<number>(120)
    const [flag, setFlag] = useState<boolean>(true)
    const layout = {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 }
    }
    const tailLayout = {
        wrapperCol: {
            offset: 6,
            span: 18
        }
    }
    const Btnshow = () => {
        form.validateFields(['phone'])
            .then(res => {
                setDisabled(false)
            })
            .catch(err => {
                setDisabled(true)
            })
    }
    const sendCaptcha = async () => {
        setFlag(false)
        clearInterval(timer)
        timer = null
        setCount(--count)
        timer = setInterval(() => {
            if (count > 0) {
                setCount(--count)
                setFlag(false)
            } else {
                clearInterval(timer)
                timer = null
                setCount(120)
                setFlag(true)
            }
        }, 1000)
        let { code, result }: any = await ajax.sendcaptcha({ phone: form.getFieldValue('phone') })
    }
    const onReset = () => {
        form.resetFields()
    }
    const onFinish = (value: any) => {
        form.validateFields()
            .then(async valid => {
                let { code, result, token }: any = await ajax.verifycaptcha(value)
                if (code == 200) {
                    sessionStorage.setItem("token", token)
                    localStorage.setItem("phone", result.phone)
                    changeUserInfo(result)
                    history.push('/main')
                }
            })
            .catch(err => {
                toast.error("请填写有效的信息")
            })
    }
    const onFinishFailed = () => {
        toast.error("请填写有效的信息")
    }
    useEffect(() => {
        var phone = new URLSearchParams(location.search).get("phone")
        if (phone) {
            form.setFieldsValue({ phone })
            setDisabled(false)
        } else {
            phone = localStorage.getItem("phone")
            if (phone) {
                form.setFieldsValue({ phone })
                setDisabled(false)
            }
        }
        clearInterval(timer)
        timer = null
        return () => {
            clearInterval(timer)
            timer = null
        }
    }, [])
    return (
        <div style={{ padding: '20px 0' }}>
            <Form {...layout} form={form} name="control-hooks" onFinish={onFinish} onFinishFailed={onFinishFailed}>
                <Form.Item name="phone" label="手机号码" rules={[{ required: true, message: '请输入手机号码' },
                { pattern: reg.phone, message: "请输入有效手机号" }]}>
                    <Input onChange={Btnshow} prefix={<PhoneOutlined />} placeholder="请输入手机号码" />
                </Form.Item>
                <Form.Item name="captcha" label="验证码" rules={[{ required: true, message: '请输入验证码' },
                { pattern: reg.code, message: '请输入4位验证码' }]}>
                    <Row>
                        <Col span={13}>
                            <Input prefix={<LockOutlined />} placeholder="请输入验证码" />
                        </Col>
                        <Col span={6} offset={1}>
                            {flag ? <Button onClick={sendCaptcha} danger disabled={disabled} type="ghost">发送验证码</Button>
                                : <Button disabled={true} type="ghost">剩余{count}S</Button>}
                        </Col>
                    </Row>
                </Form.Item>
                <Form.Item {...tailLayout}>
                    <Row>
                        <Col span={11}>
                            <Button block type="primary" htmlType="submit">
                                登录
                            </Button>
                        </Col>
                        <Col offset={2} span={11}>
                            <Button danger type="primary" block htmlType="button" onClick={onReset}>
                                重置
                            </Button>
                        </Col>
                    </Row>
                </Form.Item>
                <Form.Item {...{ wrapperCol: { span: 24 } }}>
                    <Row justify="space-between">
                        <Col>
                            <Link to="/forgetpass">忘记密码</Link>
                        </Col>
                        <Col>
                            <Link style={{ color: 'orange' }} to="/register">没有账号，先去注册</Link>
                        </Col>
                    </Row>
                </Form.Item>
            </Form>
        </div>
    )
}

export default inject("user")(observer(withRouter(LoginPhone)))